<?php

namespace Csv;
class Csv
{
    public function put_csv($list, $title)
    {
        $path = $_SERVER['DOCUMENT_ROOT'] . "/excel/csv/";
        if (!is_dir($path)) {
            mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
        }
        $file_name = "CSV" . date("mdHis", time()) . ".csv";
//        header ( 'Content-Type: application/vnd.ms-excel' );
//        header ( 'Content-Disposition: attachment;filename='.$file_name );
//        header ( 'Cache-Control: max-age=0' );
        $file_path = $path . $file_name;
        if (file_exists($file_path)) {
            unlink($file_path);
        }
        $file_paths = "/excel/csv/" . $file_name;
        $file = fopen("." . $file_paths, "a");

        $limit = 1000;
        $calc = 0;
        foreach ($title as $v) {
            $tit[] = iconv('UTF-8', 'GB2312//IGNORE', $v);
        }
        fputcsv($file, $tit);
        foreach ($list as $v) {
            $calc++;
            if ($limit == $calc) {
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach ($v as $t) {
                $tarr[] = iconv('UTF-8', 'GB2312//IGNORE', $t);
            }
            fputcsv($file, $tarr);
            unset($tarr);
        }
        unset($list);
        fclose($file);
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type . request()->server('HTTP_HOST') . $file_paths;
    }
}